# Create your views here.
#! encoding: utf-8
from django.template import Context,loader
from django.http  import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response,get_object_or_404,render,RequestContext
from goodies.models import *
from goodies.forms  import *
from django.contrib.auth import  authenticate, login
from django.core.context_processors import csrf
#from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.auth.models import User
import datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth import logout
from haystack.views import SearchView
from haystack.query import SearchQuerySet


def boiler_plate(request, c=None):
    c = c or {}
    
    c['request']   = request
    c['session']   = request.session

    c['login_form']  = LoginForm()
    c['search_blur_form'] = SearchBlurForm()
    c['recommendation']   = CelebrateList.objects.all().order_by('real_date')[:7]

    c['customer']    = request.session.get('customer')    
    if c['customer']:
        c['basket']     = request.session.get('basket')     or c['customer'].basket.count
        c['basket_sum'] = request.session.get('basket_sum') or sum([int(i.price) for i in c['customer'].basket.all()])

    c['categories']= Category.objects.all().filter(parent=None).order_by('name')
    c.update(csrf(request))
    return c

def auth_required(request):
    if not request.session.get('customer'):
        c = boiler_plate(request)
        t = 'goodies/mistake.html'
        c['mistake'] = 'Зарегестрируйтесь или залогинтесь чтобы видеть эту страницу'
        return HttpResponseRedirect('/register/')
    else:
        return False

def convert_int(x):
    try:
        return int(x)
    except:
        return None
  



def main_jquery(request,parent=None,child=None):
    c = boiler_plate(request)
    t= 'goodies/mainjquery.html'

    if parent: 
        parent = int(parent)
        get_object_or_404(Category,pk=parent)
        c['active']   = [parent]
        c['headings'] = [(parent,Category.objects.get(pk=parent).name)]
        goodies = SearchQuerySet().filter_and(categories=parent)
        if child:  
            child = int(child)
            get_object_or_404(Category,pk=child)
            c['active'].append(child)
            c['headings'].append((child,Category.objects.get(pk=child).name))
            goodies = goodies.filter_and(categories=child)
        goodies = goodies.order_by('-price').load_all()
    else:
        goodies = SearchQuerySet().order_by('-price').load_all()[:50]
        c['headings'] = [('','Новые поступления')]
   


    paginator = Paginator(goodies,20)#
    page = request.GET.get('page')#

    try:
        goodies = paginator.page(page)
    except PageNotAnInteger:
        goodies = paginator.page(1)
    except EmptyPage:
        goodies = paginator.page(paginator.num_pages)

    c['goodies'] = goodies
    c['page']       = page




    c['search_category_headings'] = c.get('headings') or ''
    
    

    c.update(csrf(request))

    return render_to_response(t,c)

def search(request):
    c = boiler_plate(request)
    c['headings']  = [('','Поиск')]


    

    f = SearchBlurForm(request.GET)
    c['search_blur_form'] = f

    if f.is_valid(): 
        goodies  = f.search()
        c['keywords']   = f.cleaned_data.get('keywords') or ''
        if c['keywords'] and not goodies:
            c['suggestion'] = goodies.spelling_suggestion()
        
    else:
        c['active']            = [request.GET.get('category')]
        return render_to_response('goodies/search_result.html',c)



    
    paginator = Paginator(goodies,20)
    page = request.GET.get('page')

    try:
        goodies = paginator.page(page)
    except PageNotAnInteger:
        goodies = paginator.page(1)
    except EmptyPage:
        goodies = paginator.page(paginator.num_pages)

    c['goodies']           = goodies
    c['page']              = page
    c['sum_pages']         = paginator.count        
    return render_to_response('goodies/search_result.html',c)



def register(request):
    if request.session.get('customer'): return HttpResponseRedirect('/personal/')

    c = boiler_plate(request)
    t = 'goodies/standart_form.html'

    if request.method == 'POST': # If the form has been submitted...
        f = RegisterForm(request.POST) # A form bound to the POST data
        if f.is_valid(): 
            request.session['customer'] = f.register()
            return HttpResponseRedirect('/main_jquery/') # Redirect after POST
    else:
        f = RegisterForm() # An unbound form

    c['form']     =  f
    c['headings'] =  [('','Регистрация')]
    return render_to_response(t, c)


def personal(request):


    t = 'goodies/standart_form.html'
    c = boiler_plate(request)
    user = c['customer']
    c['headings'] = [('','Персональная страница')]
    f = PersonalForm()
    if not user: return HttpResponseRedirect('/register/')
    
    if request.method == 'POST':
        f  =  PersonalForm(request.POST)
        if  f.is_valid():      
            request.session['customer'] = f.submit_pass(user.pk)
            return HttpResponseRedirect('/personal/')
    
    f.populate(user)
    c['form'] = f
    c.update(csrf(request))
    return render_to_response(t,c)


def login(request):


    if request.GET.get('logout'):
        del request.session['customer']
        return HttpResponseRedirect(request.GET.get('next'))


    t = 'goodies/standart_form.html'

    c = {'form_template':'goodies/login_form.html'}
    c = boiler_plate(request,c)
    
    if request.method=='POST' and not request.session.get('customer'):
        f = LoginForm(request.POST)
        if f.is_valid(): 
            request.session['customer'] = f.get_user()
            return HttpResponseRedirect(request.GET.get('next'))

    
    else: f=LoginForm()
    c['login_form'] = f

    return render_to_response(t,c)



def confirm(request):
    t = 'goodies/confirm.html'
    f = SubmitForm()

    c = {'submit_form': f}
    return render_to_response(t, c)
def basket(request):
    c    = boiler_plate(request)
    next = request.GET.get('next')
    if not c['customer']: return HttpResponseRedirect('/register/')

    add      = request.GET.get('add')
    remove   = request.GET.get('remove')
    if convert_int(add):
        item = Book.objects.get(pk=convert_int(add))
        c['customer'].basket.add(item)
        c['customer'].save()



    

    t = 'goodies/basket.html'
    
    return render_to_response(t,c)

def history(request):
    t = 'goodies/history.html'
    return render_to_response(t)

def history_item(request):
    t = 'goodies/history_item.html'
    return render_to_response(t)

def book_item(request):
    book = get_object_or_404(Book,pk = convert_int(request.GET.get('book_id')))
    

    c = boiler_plate(request)
   
    parent,child = convert_int(request.GET.get('parent')), convert_int(request.GET.get('child'))

    if parent or child:
        if child:  child  = get_object_or_404(Category, pk = convert_int(child)) 
        if parent: parent = get_object_or_404(Category, pk = convert_int(parent))
    else:
        if book.categories.count:
            ct  =  book.categories.all()[0]
            child  = ct
            parent = ct.parent or ''
        else:
            c['headings'] = [('main_jquery', 'Этой книге забыли указать категорию')]

    c['headings'] = [(i.pk,i.name) for i in (parent,child) if i] or c['headings']



    t = 'goodies/book_item.html'
    c = boiler_plate(request,c)
    c['book'] = book

    return render_to_response(t,c)



def slider(request):
    return render_to_response('goodies/slider.html')

